import React, {Component} from 'react';
import axios from 'axios';
import {connect} from 'react-redux';

class shopList extends Component {
	componentDidMount() {
		axios.get('data.json').then(res=>{
			console.log(res.data)
			this.props.setShopList(res.data);
		})
	}

	reduce(id) {
		let item = this.props.cartList.find(item=>item.id===id);
		if(item.count===1){
			this.props.removeItem(id);
		}else {
			this.props.reduceCount(id);
		}
	}

	render() {
		return (
			<div>
				<h2>Redux购物车</h2>
				<h3>商品信息</h3>
				<table className="table table-bordered">
					<thead>
						<tr>
							<th className="text-center">id</th>
							<th className="text-center">名称</th>
							<th className="text-center">价格</th>
							<th className="text-center">数量</th>
							<th className="text-center">Actions</th>
						</tr>
					</thead>
					<tbody>
					{
						this.props.shopList.map(item => {
							return (
								<tr key={item.id}>
									<td className="text-center">
										{item.id}
									</td>
									<td className="text-center">
										{item.name}
									</td>
									<td className="text-center">
										{item.price}
									</td>
									<td className="text-center">
										{
											this.props.cartList.find(value=>value.id===item.id)?
											item.count
											:
											''
										}
									</td>
									<td className="text-center">
										{
											this.props.cartList.find(value=>value.id===item.id)?
											<div>
												<button className="btn btn-primary" onClick={()=>this.props.addCount(item.id)}>+</button>
												<button className="btn btn-warning" onClick={()=>this.reduce(item.id)}>-</button>
											</div>
											:
											<button className="btn btn-primary" onClick={()=> this.props.addCart(item)}>加入购物车</button>
										}
									</td>
								</tr>
							)
						})
					}
					</tbody>
				</table>
			</div>
		);
	}
}

function mapState(state) {
	return {
		shopList: state.shopList,
		cartList: state.cartList
	}
}

function mapAction(dispatch) {
	return {
		setShopList: (data) => dispatch({
			type: 'SET_SHOP_LIST',
			data
		}),
		addCart: shopItem => dispatch({
			type: 'ADD_CART',
			shopItem
		}),
		addCount: id => dispatch({
			type: 'ADD_COUNT',
			id
		}),
		removeItem: id => dispatch({
			type: 'REMOVE_ITEM',
			id
		}),
		reduceCount: id => dispatch({
			type: 'REDUCE_COUNT',
			id
		})
	}
}

export default connect(mapState,mapAction)(shopList);